import { DataResponse, HttpModel, Service } from '../core';
import { Info } from '@/store/modules/account/info';

export interface LoginAccount {
  type?: number;
  principal: string;
  credential: string;
  rememberMe?: boolean;
}

export interface RegisterAccount {
  username: string;
  email: string;
  password: string;
}

class AccountService extends Service {
  protected create(): void {
    this.initTokenInstance('/api/account');
  }

  login = (account: LoginAccount): Promise<DataResponse<Info>> =>
    this.request({
      method: this.method.POST,
      url: '/login',
      data: account,
    });

  register = (account: RegisterAccount) =>
    this.request({
      method: this.method.POST,
      url: '/register',
      data: account,
    });

  logout = (): Promise<DataResponse<void>> =>
    this.request<HttpModel<void>>({
      method: this.method.DELETE,
      url: '/logout',
      validateStatus: (): boolean => true,
    });

  information = (): Promise<DataResponse<Info>> =>
    this.request({
      method: this.method.GET,
      url: '/information',
    });

  upgradeInfo = (): Promise<DataResponse<Info>> =>
    this.request({
      method: this.method.PUT,
      url: '/authorization',
    });

  upgradePassword = (oldPassword: string, newPassword: string): Promise<DataResponse<void>> =>
    this.request({
      method: this.method.PUT,
      url: '/password',
      data: {
        oldPassword,
        newPassword,
      },
    });

  upgradePhone = (password: string, newPhone: string): Promise<DataResponse<void>> =>
    this.request({
      method: this.method.PUT,
      url: '/phone',
      data: {
        password,
        newPhone,
      },
    });

  deletePhone = (): Promise<DataResponse<void>> =>
    this.request({
      method: this.method.DELETE,
      url: '/phone',
    });

  upgradeEmail = (password: string, newEmail: string): Promise<DataResponse<void>> =>
    this.request({
      method: this.method.PUT,
      url: '/email',
      data: {
        password,
        newEmail,
      },
    });

  deleteEmail = (): Promise<DataResponse<void>> =>
    this.request({
      method: this.method.DELETE,
      url: '/email',
    });

  upgradeAvatar = (avatar: File): Promise<DataResponse<void>> => {
    const formData = new FormData();
    formData.append('avatar', avatar);
    return this.request({
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      method: this.method.PUT,
      url: '/avatar',
      data: formData,
    });
  };
}

export const accountService = new AccountService();
